//
//  MHHomeMainViewController.m
//  ManHua
//
//  Created by 赵永泉 on 15/10/24.
//  Copyright © 2015年 蓝欧科技. All rights reserved.
//

#import "MHHomeMainViewController.h"
#import "MHHomeCategory.h"
#import "MHComicIntroduct.h"
#import "WaterFlowLayout.h"
#import "UIImage+Addiction.h"
#import "MHWaterFlowLayoutCell.h"
#import "MHComicDetailViewController.h"
#import "MHBannerViewController.h"
#import "MHHomeBanner.h"
#import "MHDataManager.h"
#import "MJRefresh.h"
#import <AFNetworking.h>
#define kHomeMainHeader @"http://112.124.96.190:9090/bukamanhua5appjobs/ComicHandle.ashx"

@interface MHHomeMainViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UICollectionViewDelegateWaterFlowLayout>
@property (nonatomic, strong) NSMutableArray *homeCategoryArray;
@property (nonatomic, strong) NSMutableArray *comicIntroductArray;
@property (nonatomic, copy) NSString *VisibleIDs;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *sizeArray;
@property (nonatomic, strong) NSMutableArray *bannerArray;
@property (nonatomic, strong) UICollectionReusableView *bannerView;
@property (nonatomic, strong) MHBannerViewController *bannerVC;
@property (nonatomic, strong) NSMutableArray *bannerIntroductArray;

@end

@implementation MHHomeMainViewController

- (NSMutableArray *)bannerIntroductArray{
    if (_bannerIntroductArray == nil) {
        _bannerIntroductArray = [NSMutableArray array];
    }
    return _bannerIntroductArray;
}

- (NSMutableArray *)bannerArray
{
    if (_bannerArray == nil) {
        _bannerArray = [NSMutableArray array];
    }
    return _bannerArray;
}

- (void)acquireCategoryData
{
    [[AFHTTPRequestOperationManager manager] GET:kHomeMainHeader parameters:[NSDictionary dictionaryWithObjects:@[@"RecommandRank"] forKeys:@[@"method"]] success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        self.homeCategoryArray = [NSMutableArray array];
        self.VisibleIDs = @"";
        [[MHDataManager shareManager]deleteValueFromeTable:@"MHHOMECategory"];
        for (NSDictionary *dict in responseObject) {
            if ([dict[@"Type"] isEqualToString:@"Book"]) {
                MHHomeCategory *homeCategory = [MHHomeCategory modelWithDict:dict];
                [self.homeCategoryArray addObject:homeCategory];
                self.VisibleIDs = [[self.VisibleIDs stringByAppendingString:homeCategory.VisibleIDs] stringByAppendingString:@"#"];
                [[MHDataManager shareManager]insertValueToTabel:@"MHHOMECategory" homeCategory:homeCategory];
            }
        }
        [self acquireComicData];
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        NSLog(@"%@", error.localizedDescription);
    }];
}

- (void)acquireComicData
{
    NSDictionary *param = [NSDictionary dictionaryWithObjects:@[self.VisibleIDs, @"search", @"2"] forKeys:@[@"name", @"method", @"type"]];
    [[AFHTTPRequestOperationManager manager] GET:kHomeMainHeader parameters:param success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        self.comicIntroductArray = [NSMutableArray array];
        [[MHDataManager shareManager]deleteValueFromeTable:@"MHHOMECOMICINTRODUCT"];
        dispatch_async(dispatch_get_global_queue(0, 0), ^{

            for (NSDictionary *dict in responseObject) {
                MHComicIntroduct *comicIntroduct = [MHComicIntroduct modelWithDict:dict];
                [self.comicIntroductArray addObject:comicIntroduct];
                [comicIntroduct calculateImageSize];
                [[MHDataManager shareManager]insertValueToTabel:@"MHHOMECOMICINTRODUCT" ComicIntroduce:comicIntroduct];
            }
            [self.collectionView.header endRefreshing];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.collectionView reloadData];
            });
        });
        
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        NSLog(@"%@", error.localizedDescription);
    }];
}

- (void)acquireBannerDate
{
    [[AFHTTPRequestOperationManager manager] GET:@"https://pi.comikon.net/banner/?format=json&platform=ios" parameters:nil success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        [[MHDataManager shareManager]deleteValueFromeTable:@"MHMHHomeBanner"];
        int i = 0;
        [self.bannerArray removeAllObjects];
        
        for (NSDictionary *dict in responseObject[@"results"]) {
            if ([dict[@"banner_type"] isEqualToString:@"bookres"]) {
                MHHomeBanner *comicIntroduct = [MHHomeBanner modelWithDict:dict];
                [comicIntroduct acquireIntroductDataWithName:dict[@"title"]];
                comicIntroduct.seq = i;
                [self.bannerArray addObject:comicIntroduct];
                i++;
            }
        }
        self.bannerVC.imageArray = self.bannerArray;
        
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        NSLog(@"%@", error.localizedDescription);
    }];
}


- (void)createBannerView
{
    CGFloat bannerH = 44.0 / 64.0 * Width;
    MHBannerViewController *bannerVC = [[MHBannerViewController alloc]init];
    __weak MHHomeMainViewController *test = self;
    bannerVC.buttonClickBlock = ^(NSInteger number)
    {
        if (number == test.bannerArray.count) {
            number = 0;
        }
        MHComicDetailViewController *comicDetailVC = [[MHComicDetailViewController alloc]init];
        comicDetailVC.comicIntroduct = [test.bannerArray[number] comicIntroduct];
        [test.navigationController pushViewController:comicDetailVC animated:YES];
    };
    self.bannerView = [[UICollectionReusableView alloc]initWithFrame:CGRectMake(0, 64, Width, bannerH)];
    [self.bannerView addSubview:bannerVC.contentView];
    self.bannerVC = bannerVC;
    self.bannerView.frame = CGRectMake(0, 0, Width, bannerH);
    [self.collectionView addSubview:self.bannerView];
    self.bannerVC.imageArray = self.bannerArray;
}

- (void)reloadBanner:(NSNotification *)notification
{
    [self.bannerVC setImageURL:notification.userInfo[@"url"] WithIndex:[notification.userInfo[@"index"] integerValue]];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [[MHDataManager shareManager]createTable];
    self.homeCategoryArray=   [[MHDataManager shareManager]findMainTopicModelData:@"MHHOMECategory"];
    self.comicIntroductArray=[[MHDataManager shareManager]findMainTopicModelData:@"MHHOMECOMICINTRODUCT"];
    self.bannerArray=[[MHDataManager shareManager]findMainTopicModelData:@"MHMHHomeBanner"];
    
    if (self.homeCategoryArray.count!=0&&self.comicIntroductArray.count!=0) {
        for (MHComicIntroduct *comicIntroduct in self.comicIntroductArray) {
            [comicIntroduct calculateImageSize];
        }
    }
    [self acquireBannerDate];
    [self acquireCategoryData];
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBar.titleTextAttributes = [NSDictionary dictionaryWithObjectsAndKeys:kThemeColor,UITextAttributeTextColor,nil];
    self.title = @"首页";


    WaterFlowLayout *water = [[WaterFlowLayout alloc]initWithNumbersOfColumns:2];
    water.minimumInteritemSpacing = 10;
    water.minimumLineSpacing = 10;
    water.sectionInset = UIEdgeInsetsMake(20, 10, 20, 10);
    water.delegate = self;
    water.headerReferenceSize = CGSizeMake(Width, 44.0 / 64.0 * Width);
    
    UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 64, Width, Height - 64 - 44) collectionViewLayout:water];
    collectionView.backgroundColor = [UIColor whiteColor];
    collectionView.header=[MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self acquireBannerDate];
        [self acquireCategoryData];
    } ];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    
    [self.view addSubview:collectionView];
    self.collectionView = collectionView;
    [self.collectionView registerClass:[MHWaterFlowLayoutCell class] forCellWithReuseIdentifier:@"waterFlowLayout"];
    
    [self createBannerView];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadBanner:) name:@"imageUrl" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadWaterFlow) name:@"calculateSize" object:nil];
}

- (void)reloadWaterFlow
{
    [self.collectionView reloadData];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.comicIntroductArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MHWaterFlowLayoutCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"waterFlowLayout" forIndexPath:indexPath];
    cell.comicIntroct = self.comicIntroductArray[indexPath.row];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(WaterFlowLayout *)layout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MHComicIntroduct *comicIntroduct = self.comicIntroductArray[indexPath.item];
    CGSize size = comicIntroduct.imageSize;
    if (CGSizeEqualToSize(size, CGSizeZero)) {
        return CGSizeMake(100, 100);
    }
    else
        return size;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    MHComicDetailViewController *comicDetailVC = [[MHComicDetailViewController alloc]init];
    comicDetailVC.comicIntroduct = self.comicIntroductArray[indexPath.row];
    [self.navigationController pushViewController:comicDetailVC animated:YES];
}

@end
